<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import {
  showLoading,
  hideLoading,
  showToast,
  navigateTo,
  reLaunch,
  getCurrentInstance,
} from '@tarojs/taro';
import { MaskClose as AppNutIconMaskClose } from '@nutui/icons-vue-taro';
import { ASSET_DETAIL_QUERY } from '/@/api/modules/equipment/asset-manage';
import { QUERY_DICT_BY_PARENT_ID } from '/@/api/modules/base/dict';
import { INSERT_WORK_ORDER } from '/@/api/modules/order/work-order';
import { UPLOAD_APP_WORK_ORDER_BY_TASK_ASSET } from '/@/api/modules/maintain/plan-task';
import { QUERY_ALARM_DETAIL } from '/@/api/modules/base/alarm';
import { ALARM_DEAL } from '/@/api/modules/base/alarm';
import { formRules } from './state';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
/**
 * @description 当前路由信息
 *
 **/
const params = getCurrentInstance().router?.params as unknown as {
  planTaskId?: string;
  /**
   * 资产id
   */
  assetId?: string;
  /**
   * 告警id
   */
  alarmId?: string;
  from?: string;
};

const workOrderFormRef = ref();

const state = reactive<{
  /**
   * 工单子类型列表
   */
  taskTypeList: AppSysDict.Dto[];
  /**
   * 工单子类型列表
   */
  taskSubTypeList: AppSysDict.Dto[];
  /**
   * 工单子类型选择器是否显示
   */
  taskTypePickerIsShow: boolean;
  /**
   * 工单子类型选择器是否显示
   */
  taskSubTypePickerIsShow: boolean;
  /**
   * 区域列表弹出层是否显示
   */
  appRegionListPopupIsShow: boolean;
  /**
   * 资产列表弹出层是否显示
   */
  appAssetListPopupIsShow: boolean;
  /**
   * taro应用环境
   */
  taroEnv: string;
}>({
  taskTypeList: [],
  taskSubTypeList: [],
  taskTypePickerIsShow: false,
  taskSubTypePickerIsShow: false,
  appRegionListPopupIsShow: false,
  appAssetListPopupIsShow: false,
  taroEnv: process.env.TARO_ENV,
});

const formState = reactive<AppSysWorkOrder.Dto>({
  orderTypeId: '',
  orderTypeCode: '',
  orderTypeName: '',
  orderSubTypeId: '',
  orderSubTypeCode: '',
  orderSubTypeName: '',
  areaId: '',
  areaName: '',
  assetId: '',
  assetName: '',
  description: '',
  workOrderFileDto: [],
  status: 'task_assign',
  organizationId: '',
  organizationName: '',
});

/**
 * @function 上传文件
 * @param imgList
 */
function uploadImageChange(imgList: { key: string; src: string }[]) {
  (
    imgList.map((i) => {
      return {
        fileType: 1,
        fileUrl: i.src,
        fileName: i.src.split('/').reverse()[0],
      };
    }) as AppSysWorkOrder.FileDto[]
  ).forEach((item) => {
    formState.workOrderFileDto?.push(item);
  });
}

/**
 * @function 确认提交
 */
function submit() {
  workOrderFormRef.value.validate().then(({ valid }) => {
    if (!valid) return;
    showLoading({ title: '加载中...' });

    INSERT_WORK_ORDER({ workOrderDto: formState }).then((res) => {
      if (params.from && ['inspection', 'maintenance'].includes(params.from)) {
        UPLOAD_APP_WORK_ORDER_BY_TASK_ASSET({
          workOrderId: res.workOrderDto.id,
          orderCode: res.workOrderDto.orderCode,
          planTaskAssetId: params.planTaskId,
        }).then((response) => {
          hideLoading();
          showToast({
            title: response.comResp?.msg || response.comResp?.tip || '',
            icon: 'success',
          });
          navigateTo({
            url: `/pages/work-order/submit-success/index?id=${res.workOrderDto.id}`,
          }).then(() => {
            formState.areaId = '';
            formState.areaName = '';
            formState.assetId = '';
            formState.assetName = '';
            formState.description = '';
            formState.workOrderFileDto = [];
            formState.status = 'task_assign';
          });
        });
        return;
      }

      /**
       * 页面来源-告警详情
       */
      if (params.from === 'alarm-handle' && params.alarmId) {
        ALARM_DEAL({
          content: {
            id: params.alarmId,
            dealType: 1,
            dealTime: new Date().valueOf(),
            dealWorkOrder: res.workOrderDto.id,
          },
        }).then((res2) => {
          hideLoading();
          showToast({
            title: res2.comResp.msg || res2.comResp.tip || '',
            icon: 'success',
            success() {
              setTimeout(() => {
                navigateTo({
                  url: `/pages/work-order/submit-success/index?id=${res.workOrderDto.id}`,
                });
              }, 2000);
            },
          });
        });
        return;
      }

      hideLoading();
      showToast({
        title: res.comResp.msg || res.comResp.tip || '',
        icon: 'success',
      });
      navigateTo({
        url: `/pages/work-order/submit-success/index?id=${res.workOrderDto.id}`,
      });
    });
  });
}

onMounted(() => {
  // 设置维修工单类型
  QUERY_DICT_BY_PARENT_ID({
    parentTag: 'task_type',
  }).then((res) => {
    if (!res.content || !res.content.length) return;

    state.taskTypeList = res.content;
    // 维修工单索引
    const idx = res.content.findIndex((item) => {
      return item.dictTag === 'task_repair';
    });

    formState.orderTypeId = res.content[idx].id;
    formState.orderTypeCode = res.content[idx].dictTag;
    formState.orderTypeName = res.content[idx].dictName;
  });

  // 设置工单来源
  QUERY_DICT_BY_PARENT_ID({ parentTag: 'task_source' }).then((res) => {
    if (!res.content || !res.content.length) return;

    // 工单来源索引
    const idx = res.content.findIndex((item) => {
      return item.dictTag === 'task_app';
    });

    formState.orderSourceId = res.content[idx].id;
    formState.orderSourceCode = res.content[idx].dictTag;
    formState.orderSourceName = res.content[idx].dictName;
  });

  // 获取工单子类
  QUERY_DICT_BY_PARENT_ID({
    parentTag: 'task_sub_type',
  }).then((res) => {
    state.taskSubTypeList = res.content;
  });

  /**
   * 处理来自不同页面
   * from inspection/maintenance/scan
   */
  if (params.from && params.assetId) {
    ASSET_DETAIL_QUERY({ ids: [params.assetId!] }).then((res) => {
      formState.assetId = res.assetInfo?.id;
      formState.assetName = res.assetInfo?.assetName;
      // formState.areaId = res.assetInfo?.areaId;
      // formState.areaName = res.assetInfo?.areaName;
    });
  }

  /**
   * 页面来源-告警详情
   */
  if (params.from === 'alarm-handle' && params.alarmId) {
    QUERY_ALARM_DETAIL({ id: params.alarmId }).then((res) => {
      formState.areaName = res.content.areaName;
      formState.assetId = res.content.alarmResType === 5 ? res.content.alarmResId : '';
      formState.assetName = res.content.alarmResType === 5 ? res.content.alarmResName : '';
    });
  }
  /**
   * 当前用户部门
   */
  LOGIN_APP().then((res) => {
    if (res.organDtos && res.organDtos.length > 0) {
      const organ = res.organDtos[0];
      formState.organizationId = organ.id || '';
      formState.organizationName = organ.name || '';
    }
  });
});
</script>

<template>
  <view class="work-order-edit app-page--1">
    <app-navbar title="故障上报" />
    <nut-tabs
      model-value="push"
      @click="
        ({ paneKey }) => {
          if (paneKey === 'record') {
            reLaunch({ url: '/pages/work-order/list/index?pageType=report-history' });
          }
        }
      "
    >
      <nut-tab-pane title="新建上报" pane-key="push" />
      <nut-tab-pane title="上报记录" pane-key="record" />
    </nut-tabs>
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="work-order-edit__wrapper">
        <nut-form
          :model-value="formState"
          :rules="formRules"
          class="work-order-edit__form"
          ref="workOrderFormRef"
          body-align="right"
        >
          <nut-form-item
            required
            label="工单类型"
            prop="orderTypeId"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="formState.orderTypeName"
              placeholder="请选择工单类型"
              :border="false"
              input-align="right"
              readonly
              @click="state.taskTypePickerIsShow = !state.taskTypePickerIsShow"
            />
          </nut-form-item>
          <nut-form-item
            required
            label="子类"
            prop="orderSubTypeId"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="formState.orderSubTypeName"
              placeholder="请选择工单子类型"
              :border="false"
              readonly
              input-align="right"
              @click="state.taskSubTypePickerIsShow = !state.taskSubTypePickerIsShow"
            />
          </nut-form-item>
          <nut-form-item
            required
            label="所在位置"
            prop="areaName"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              v-model="formState.areaName"
              placeholder="请输入所在位置"
              :border="false"
              input-align="right"
            />
          </nut-form-item>
          <nut-form-item
            label="故障设备"
            prop="assetId"
            label-align="left"
            error-message-align="left"
          >
            <view class="work-order-edit__form-asset-wrapper">
              <nut-input
                class="work-order-edit__form-asset-input"
                :model-value="formState.assetName"
                placeholder="请选择故障设备"
                :border="false"
                readonly
                @click="
                  () => {
                    if (params.from && params.assetId) {
                      state.appAssetListPopupIsShow = false;
                    } else {
                      state.appAssetListPopupIsShow = !state.appAssetListPopupIsShow;
                    }
                  }
                "
                input-align="right"
              />
              <app-nut-icon-mask-close
                v-if="formState.assetId"
                class="work-order-edit__form-asset-del-btn"
                @click="
                  () => {
                    formState.assetId = undefined;
                    formState.assetName = undefined;
                  }
                "
              />
            </view>
          </nut-form-item>
          <nut-form-item label="工单描述" />
          <nut-form-item>
            <nut-textarea
              v-model="formState.description"
              placeholder="填写申请说明"
              rows="8"
              limit-show
              text-align="left"
              max-length="200"
            />
          </nut-form-item>
          <nut-form-item label="语音">
            <app-wx-record-audio
              v-if="state.taroEnv === 'weapp'"
              @change="(url: string, fileName: string) => {
                formState.workOrderFileDto?.splice(formState.workOrderFileDto.findIndex((item) => {
                  return item.fileType === 2;
                }), 1);
                formState.workOrderFileDto?.push({
                  fileType: 2,
                  fileName,
                  fileUrl: url,
                })
              }"
            />
            <app-dd-record-audio
              v-else
              @change="(url: string) => {
                formState.workOrderFileDto?.splice(formState.workOrderFileDto.findIndex((item) => {
                  return item.fileType === 2;
                }), 1);
                formState.workOrderFileDto?.push({
                  fileType: 2,
                  fileName: url.split('/').reverse()[0],
                  fileUrl: url,
                })
              }"
            />
          </nut-form-item>
          <nut-form-item label="上传图片">
            <app-upload-image @on-change="uploadImageChange" module="repair" />
          </nut-form-item>
        </nut-form>
      </view>
    </scroll-view>
    <view class="work-order-edit__footer">
      <nut-button block type="info" @click="submit"> 提交 </nut-button>
    </view>

    <nut-popup v-model:visible="state.taskTypePickerIsShow" position="bottom">
      <nut-picker
        title="请选择工单类型"
        :model-value="[formState.orderTypeId as string]"
        :columns="
          state.taskTypeList.map((v) => {
            return { text: v.dictName, value: v.id };
          })
        "
        @confirm="
          ({ selectedValue, selectedOptions }) => {
            if (!selectedValue[0]) return;

            formState.orderTypeCode =
              state.taskTypeList[
                state.taskTypeList.findIndex((t) => {
                  return t.id === selectedValue[0];
                })
              ].dictTag;
            formState.orderTypeId = selectedOptions[0].value;
            formState.orderTypeName = selectedOptions[0].text;
            formState.orderSubTypeCode = '';
            formState.orderSubTypeId = '';
            formState.orderSubTypeName = '';
            state.taskTypePickerIsShow = false;
          }
        "
        @cancel="state.taskTypePickerIsShow = false"
      />
    </nut-popup>

    <nut-popup v-model:visible="state.taskSubTypePickerIsShow" position="bottom">
      <nut-picker
        title="请选择工单子类型"
        :model-value="[formState.orderSubTypeId as string]"
        :columns="
          state.taskSubTypeList
            .filter((v) => {
              return v.dictTag.includes(formState.orderTypeCode || '');
            })
            .map((v) => {
              return { text: v.dictName, value: v.id };
            })
        "
        @confirm="
          ({ selectedValue, selectedOptions }) => {
            if (!selectedValue[0]) return;

            formState.orderSubTypeCode =
              state.taskSubTypeList[
                state.taskSubTypeList.findIndex((t) => {
                  return t.id === selectedValue[0];
                })
              ].dictTag;
            formState.orderSubTypeId = selectedOptions[0].value;
            formState.orderSubTypeName = selectedOptions[0].text;
            state.taskSubTypePickerIsShow = false;
          }
        "
        @cancel="state.taskSubTypePickerIsShow = false"
      />
    </nut-popup>
    <app-asset-list-popup
      v-model="state.appAssetListPopupIsShow"
      title="故障设备"
      :options="{
        assetInfo: {
          areaId: formState.areaId,
        },
      }"
      @on-selected="(assetItem: AssetInfo.Dto) => {
        formState.assetId = assetItem.id;
        formState.assetName = assetItem.assetName;
        state.appAssetListPopupIsShow = !state.appAssetListPopupIsShow;
      }"
    />
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
